#!/usr/bin/env python
# -*- coding: utf-8 -*-

from functools import partial


class Env(object):
    def __init__(self, rpc):
        self.rpc = rpc

    @property
    def version(self):
        return self.rpc.version

    @property
    def sid(self):
        return self.rpc.sid

    @property
    def session(self):
        return self.rpc.session

    def __getitem__(self, index):
        # print('env, name, ', index)
        MyModel = OdooRpcModel
        return MyModel(index, self)

    def ref2(self, xmlid):
        res = self['ir.model.data'].xmlid_to_res_model_res_id(xmlid, True)
        return res

    def ref(self, xmlid):
        res = self['ir.model.data'].xmlid_to_res_model_res_id(xmlid, True)
        return res[1]


class OdooRpcModel(object):
    def __init__(self, model, env):
        self.model = model
        self.env = env
        self.rpc = env.rpc
        # self.env = Env(rpc)

    def __getattr__(self, attr):
        return partial(self.rpc.web_dataset_call_kw, self.model, attr)
        # return partial(self.rpc.execute, self.model, attr)

    def rpccall(self, method, *args, **kwargs):
        return self.rpc.web_dataset_call_kw(self.model, method, *args, **kwargs)

    # 需要搬家到 odoorpc 中的

    def rpc_find_or_create(self, domain, values):
        res = self.search(domain, limit=1)
        if res:
            return res[0]
        res = self.create(values)
        return res[0]

    def rpc_update_or_create(self, domain, values):
        res = self.search(domain, limit=1)
        if res:
            self.write(res, values)
            return res[0]

        res = self.create(values)
        return res[0]
